﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using QLKS.BLL;
using QLKS.Entity;
using System.Linq;

namespace QLKS.Views
{
    public partial class PhieuThuePhong_View : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                ViewState["Order"] = string.Empty;
                ViewState["Sort"] = string.Empty;
                ViewState["action"] = string.Empty;

                EnableControl();
                Reload();
                ReloadDetail(ViewState["detail"] as List<ChiTietPhieuThuePhong>);
                //
                LoadLoaiPhong();
                LoadLoaiKhachHang();
            }
        }

        #region Private Method

        void Reload()
        {
            List<PhieuThuePhong> lstData = PhieuThuePhongBUS.GetByAll(new PhieuThuePhong());
            this.gvMain.DataSource = QLKS.Common.Extensions.Sort_List<PhieuThuePhong>(ViewState["Order"].ToString(), ViewState["Sort"].ToString(), lstData);
            this.gvMain.DataBind();
        }
        
        void ViewAddUpdatePanel(bool bflag)
        {
            this.pnlMain.Visible = bflag;
            this.pnlUpdate.Visible = !bflag;
        }

        void EnableControl()
        {
            switch (ViewState["action"].ToString())
            {
                case "Add":
                case "Edit":
                    this.btnNew.Enabled = false;
                    this.btnDelete.Enabled = false;
                    this.btnEdit.Enabled = false;
                    this.btnSave.Enabled = true;
                    this.btnCancel.Enabled = true;
                    break;
                default:
                    this.btnNew.Enabled = true;
                    this.btnDelete.Enabled = true;
                    this.btnEdit.Enabled = true;
                    this.btnSave.Enabled = false;
                    this.btnCancel.Enabled = false;
                    break;
            }
        }

        void Clear()
        {
            foreach (Control ctrl in pnlUpdate.Controls)
            {
                if (ctrl is TextBox)
                    ((TextBox)ctrl).Text = string.Empty;
            }
        }

        void ShowAlert(string message)
        {
            string cleanMessage = message.Replace("'", "\'");
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + cleanMessage + "')</script>";
            Page.Controls.Add(lbl);
        }

        void LoadLoaiPhong()
        {
            try
            {
                ddlLoaiPhong.DataTextField = "TenLoaiPhong";
                ddlLoaiPhong.DataValueField = "MaLoaiPhong";
                ddlLoaiPhong.DataSource = QLKS.Common.Extensions.Sort_List("ASC", "TenLoaiPhong", DMLoaiPhongBUS.GetByAll(new DMLoaiPhong()));
                ddlLoaiPhong.DataBind();
            }
            catch (Exception) { }
            finally
            {
                ddlLoaiPhong.Items.Insert(0, new ListItem("Chọn loại phòng", "0"));
                ddlLoaiPhong.SelectedIndex = 0;
            }
            //
            ddlLoaiPhong_SelectedIndexChanged(new object(), new EventArgs());
        }
        
        void LoadPhongThue(int loaiPhongID)
        {
            try
            {
                if (loaiPhongID != 0)
                {
                    DMPhong obj = new DMPhong();
                    obj.LoaiPhongID = loaiPhongID;
                    List<DMPhong> lstData = DMPhongBUS.GetByAll(obj);
                    if (ViewState["action"].ToString() == "Add")
                        lstData = lstData.FindAll(item => item.TinhTrang == false);
                    //
                    ddlPhongThue.DataTextField = "TenPhong";
                    ddlPhongThue.DataValueField = "MaPhong";
                    ddlPhongThue.DataSource = QLKS.Common.Extensions.Sort_List("ASC", "TenPhong", lstData);
                    ddlPhongThue.DataBind();
                }
            }
            catch (Exception) { }
            finally
            {
                ddlPhongThue.Items.Insert(0, new ListItem("Chọn phòng thuê", "0"));
                ddlPhongThue.SelectedIndex = 0;
            }
        }

        void ReloadDetail(List<ChiTietPhieuThuePhong> listDetail)
        {
            if (listDetail == null)
            {
                listDetail = new List<ChiTietPhieuThuePhong>();
            }
            this.gvDetail.DataSource = listDetail;
            this.gvDetail.DataBind();

            upDetail.Update();
        }

        List<ChiTietPhieuThuePhong> GetDetail()
        {
            List<ChiTietPhieuThuePhong> listDetail = new List<ChiTietPhieuThuePhong>();
            try
            {
                ChiTietPhieuThuePhong obj;
                foreach (GridViewRow item in gvDetail.Rows)
                {
                    obj = new ChiTietPhieuThuePhong();
                    Label lbl = item.FindControl("lblID") as Label;
                    obj.KhachHangID = Convert.ToInt32((lbl == null || lbl.Text == "") ? "0" : lbl.Text.ToString());
                    if (obj.KhachHangID != null && obj.KhachHangID != 0)
                        listDetail.Add(obj);
                }
            }
            catch { listDetail = null; }

            return listDetail;
        }

        void LoadLoaiKhachHang()
        {
            try
            {
                ddlLoaiKhachHang.DataTextField = "TenLoaiKhachHang";
                ddlLoaiKhachHang.DataValueField = "MaLoaiKhachHang";
                ddlLoaiKhachHang.DataSource = QLKS.Common.Extensions.Sort_List("ASC", "TenLoaiKhachHang", DMLoaiKhachHangBUS.GetByAll(new DMLoaiKhachHang()));
                ddlLoaiKhachHang.DataBind();
            }
            catch (Exception) { }
            finally
            {
                ddlLoaiKhachHang.Items.Insert(0, new ListItem("Chọn loại khách hàng", "0"));
                ddlLoaiKhachHang.SelectedIndex = 0;
            }
        }
        
        #endregion

        #region Event On Page

        protected void gvMain_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.gvMain.PageIndex = e.NewPageIndex;
            this.Reload();
        }

        protected void gvMain_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                ((CheckBox)e.Row.FindControl("chkall")).Attributes.Add("onclick", "javascript:SelectAll('" + gvMain.ClientID + "','" + ((CheckBox)e.Row.FindControl("chkall")).ClientID + "')");
            }
        }

        protected void gvMain_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (this.ViewState["Sort"].ToString() != e.SortExpression)
            {
                this.ViewState["Sort"] = e.SortExpression;
                this.ViewState["Order"] = "DESC";
            }
            else
            {
                if (ViewState["Order"].ToString() == "")
                    this.ViewState["Order"] = "DESC";
                else
                {
                    if (ViewState["Order"].ToString() == "DESC")
                    {
                        this.ViewState["Order"] = "ASC";
                    }
                    else
                    {
                        this.ViewState["Order"] = "DESC";
                    }
                }
            }
            Reload();
        }

        protected void gvKhachHang_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                ((CheckBox)e.Row.FindControl("chkall")).Attributes.Add("onclick", "javascript:SelectAll('" + gvMain.ClientID + "','" + ((CheckBox)e.Row.FindControl("chkall")).ClientID + "')");
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            ViewState["action"] = "Add";
            EnableControl();
            ViewAddUpdatePanel(false);
            Clear();
            this.txtNgayThuePhong.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
            //
            ReloadDetail(new List<ChiTietPhieuThuePhong>());
            ViewState["Detail"] = null;
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (isRefresh) return;
            bool result = false;
            int count = 0;
            try
            {
                CheckBox chk;
                PhieuThuePhong obj;
                foreach (GridViewRow r in gvMain.Rows)
                {
                    chk = r.FindControl("chkid") as CheckBox;
                    if (chk.Checked)
                    {
                        result = true;
                        Label lbl = r.FindControl("lblID") as Label;
                        obj = new PhieuThuePhong();
                        obj.MaPhieuThuePhong = Convert.ToInt32((lbl == null || lbl.Text == "") ? "0" : lbl.Text.ToString());
                        if (PhieuThuePhongBUS.Delete(obj))
                            count += 1;
                    }
                }
                if (count == 0) ShowAlert("Chưa dòng thông tin nào được chọn để xóa.");
            }
            catch (Exception)
            {
                ShowAlert("Lỗi khi thao tác dữ liệu.");
                result = false;
            }
            finally
            {
                if (result)
                {
                    ShowAlert("Xóa dữ liệu thành công. Tổng số dòng được xóa:" + count.ToString() + " dòng.");
                    Reload();
                }
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            if (isRefresh) return;
            bool result = false;
            ViewState["action"] = "Edit";
            try
            {
                CheckBox chk;
                PhieuThuePhong obj = new PhieuThuePhong();
                foreach (GridViewRow r in gvMain.Rows)
                {
                    chk = r.FindControl("chkid") as CheckBox;
                    if (chk.Checked)
                    {
                        result = true;
                        Label lbl = r.FindControl("lblID") as Label;
                        obj.MaPhieuThuePhong = Convert.ToInt32((lbl == null || lbl.Text == "") ? "0" : lbl.Text.ToString());
                        ViewState["OldCode"] = obj.MaPhieuThuePhong;
                        List<PhieuThuePhong> lstData = PhieuThuePhongBUS.GetByAll(obj);
                        if (lstData.Count == 1)
                        {
                            this.ddlLoaiPhong.SelectedIndex = QLKS.Common.Extensions.GetIndexDropDownList(ddlLoaiPhong, lstData[0].PhongThue.LoaiPhongID);
                            this.ddlLoaiPhong_SelectedIndexChanged(new object(), new EventArgs());
                            this.ddlPhongThue.SelectedIndex = QLKS.Common.Extensions.GetIndexDropDownList(ddlPhongThue, lstData[0].PhongThueID);
                            this.txtNgayThuePhong.Text = lstData[0].NgayThuePhong;
                            this.txtGhiChu.Text = lstData[0].GhiChu;
                            //detail
                            ReloadDetail(lstData[0].ListDetail);
                            ViewState["detail"] = lstData[0].ListDetail;
                        }
                        break;
                    }
                }
                if (!result) ShowAlert("Chưa dòng thông tin nào được chọn.");
            }
            catch (Exception)
            {
                ShowAlert("Lỗi khi thao tác dữ liệu.");
                result = false;
            }
            finally
            {
                if (result)
                {
                    EnableControl();
                    ViewAddUpdatePanel(false);
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (isRefresh) return;
            bool result = false;
            try
            {
                PhieuThuePhong obj = new PhieuThuePhong();
                obj.PhongThueID = Convert.ToInt32(this.ddlPhongThue.SelectedValue);
                obj.NgayThuePhong = QLKS.Common.Extensions.FuncDateChange(this.txtNgayThuePhong.Text.Trim());
                obj.GhiChu = this.txtGhiChu.Text.Trim();
                //
                obj.ListDetail = GetDetail();

                if (ViewState["action"].ToString() == "Add")
                {
                    result = PhieuThuePhongBUS.Insert(obj);
                }
                else if (ViewState["action"].ToString() == "Edit")
                {
                    obj.MaPhieuThuePhong = Convert.ToInt32(ViewState["OldCode"]);
                    result = PhieuThuePhongBUS.Update(obj);
                }
            }
            catch (Exception)
            {
                ShowAlert("Lỗi khi thao tác dữ liệu.");
                result = false;
            }
            finally
            {
                if (result)
                {
                    ShowAlert("Dữ liệu đã được cập nhật.");
                    this.btnCancel_Click(new object(), new EventArgs());
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ViewState["action"] = string.Empty;
            EnableControl();
            ViewAddUpdatePanel(true);
            Clear();
            Reload();
        }

        protected void ddlLoaiPhong_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadPhongThue(Convert.ToInt32(ddlLoaiPhong.SelectedValue));
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            bool result = false;
            List<ChiTietPhieuThuePhong> detail;
            if (ViewState["detail"] == null)
            {
                detail = new List<ChiTietPhieuThuePhong>();
            }
            else
            {
                detail = ViewState["detail"] as List<ChiTietPhieuThuePhong>;
            }
            try
            {
                DMKhachHang obj = new DMKhachHang();
                obj.TenKhachHang = this.txtTenKhachHang.Text.Trim();
                obj.LoaiKhachHangID = Convert.ToInt32(this.ddlLoaiKhachHang.SelectedValue);
                obj.CMND = this.txtCMND.Text.Trim();
                obj.DienThoai = this.txtDienThoai.Text.Trim();
                obj.Email = this.txtEmail.Text.Trim();
                obj.DiaChi = this.txtDiaChi.Text.Trim();
                //
                result = DMKhachHangBUS.Insert(obj);
                if (result)
                {
                    List<DMKhachHang> kh = DMKhachHangBUS.GetByAll(obj);
                    if (kh.Count > 0)
                    {
                        ChiTietPhieuThuePhong ct = new ChiTietPhieuThuePhong();
                        ct.KhachHangID = kh[0].MaKhachHang;
                        ct.KhachHang = kh[0];
                        detail.Add(ct);
                    }
                }
            }
            catch (Exception)
            {
                result = false;
            }
            finally
            {
                ViewState["detail"] = detail;
                ReloadDetail(detail);
            }
            //
            mpePopup.Hide();
        }

        #endregion

        #region Browser Refresh

        private bool refreshState;
        private bool isRefresh;

        protected override void LoadViewState(object savedState)
        {
            object[] AllStates = (object[])savedState;
            base.LoadViewState(AllStates[0]);
            refreshState = bool.Parse(AllStates[1].ToString());
            if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
                isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
        }

        protected override object SaveViewState()
        {
            Session["ISREFRESH"] = refreshState;
            object[] AllStates = new object[3];
            AllStates[0] = base.SaveViewState();
            AllStates[1] = !(refreshState);
            return AllStates;
        }

        #endregion 
        
    }
}